package com.ruoyi.develop.payRecord.controller;

import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.finance.financeAp.service.IFinanceApService;
import com.ruoyi.develop.lvBuy.domain.LvBuy;
import com.ruoyi.develop.lvBuy.service.ILvBuyService;
import com.ruoyi.develop.orderIronRecordBuy.domain.OrderIronRecordBuy;
import com.ruoyi.develop.orderIronRecordBuy.service.IOrderIronRecordBuyService;
import com.ruoyi.develop.payApply.domain.PayApply;
import com.ruoyi.develop.payApply.service.IPayApplyService;
import com.ruoyi.develop.payApplyBuyDetail.domain.PayApplyBuyDetail;
import com.ruoyi.develop.payApplyBuyDetail.service.IPayApplyBuyDetailService;
import com.ruoyi.develop.payRecordBuyDetail.domain.PayRecordBuyDetail;
import com.ruoyi.develop.payRecordBuyDetail.service.IPayRecordBuyDetailService;
import com.ruoyi.develop.process.processPayApply.service.IProcessPayApplyService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.payRecord.domain.PayRecord;
import com.ruoyi.develop.payRecord.service.IPayRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 付款记录Controller
 *
 * @author lmm
 * @date 2024-10-27
 */
@RestController
@RequestMapping("/payRecord/payRecord")
public class PayRecordController extends BaseController {
    @Autowired
    private IPayRecordService payRecordService;
    @Autowired
    private IPayApplyService payApplyService;
    @Autowired
    private ILvBuyService lvBuyService;
    @Autowired
    private IPayApplyBuyDetailService payApplyBuyDetailService;
    @Autowired
    private IPayRecordBuyDetailService payRecordBuyDetailService;
    @Autowired
    private IProcessPayApplyService processPayApplyService;
    @Autowired
    private IFinanceApService financeApService;
    @Autowired
    private IOrderIronRecordBuyService orderIronRecordBuyService;




    /**
     * 查询付款记录列表
     */
    @PreAuthorize("@ss.hasPermi('develop:PayRecord:query')")
    @GetMapping("/list")
    public TableDataInfo list(PayRecord entity) {
        startPage();
        List<PayRecord> list = payRecordService.selectList(entity);
        return getDataTable(list);
    }

    /**
     * 导出付款记录列表
     */
    @PreAuthorize("@ss.hasPermi('develop:PayRecord:export')")
    @Log(title = "付款记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PayRecord entity) {
        List<PayRecord> list = payRecordService.selectList(entity);
        ExcelUtil<PayRecord> util = new ExcelUtil<PayRecord>(PayRecord.class);
        util.exportExcel(response, list, "付款记录数据");
    }

    /**
     * 获取付款记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:PayRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(payRecordService.selectById(id));
    }

    /**
     * 新增付款记录
     */
    @PreAuthorize("@ss.hasPermi('develop:PayRecord:add')")
    @Log(title = "付款记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody PayRecord entity) {
        return toAjax(payRecordService.insert(entity));
    }

    /**
     * 修改付款记录
     */
    @PreAuthorize("@ss.hasPermi('develop:PayRecord:edit')")
    @Log(title = "付款记录", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody PayRecord entity) {
        return toAjax(payRecordService.update(entity));
    }

    /**
     * 删除付款记录
     */
    @PreAuthorize("@ss.hasPermi('develop:PayRecord:remove')")
    @Log(title = "付款记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(payRecordService.deleteByIds(ids));
    }


    /**
     * 取消付款
     */
    @PreAuthorize("@ss.hasPermi('develop:PayRecord:remove')")
    @Log(title = "取消付款", businessType = BusinessType.DELETE)
    @DeleteMapping("cancel/{ids}")
    public AjaxResult cancel(@PathVariable String[] ids) {
        return toAjax(payRecordService.cancelByIds(ids));
    }


    /**
     * 新增付款记录
     */
    @PreAuthorize("@ss.hasPermi('develop:PayRecord:add')")
    @Log(title = "付款记录", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping("/payAdd")
    public AjaxResult payAdd(@RequestBody PayRecord entity) {
        String applyId = entity.getApplyId();
        // 先判断 申请单 是否已经付款
        if (StringUtils.isBlank(applyId)) {
            return AjaxResult.error("申请单ID不能为空");
        }
        if (StringUtils.isNotBlank(applyId)) {
            PayApply apply = payApplyService.selectById(applyId);
            if (BusinessConstants.PAY_APPLY_PAY_STATUS_PAID.equals(apply.getPayStatus())) {
                return AjaxResult.error("该申请单已经完成付款");
            } else {
                BigDecimal remainMoney = apply.getRemainMoney();
                BigDecimal payMoney = entity.getMoney();
                // 如果支付金额 大于剩余金额 则不能支付
                if (payMoney.compareTo(remainMoney) > 0) {
                    return AjaxResult.error("支付金额不能大于剩余金额");
                }
                apply.setPaidMoney(apply.getPaidMoney().add(payMoney));
                apply.setRemainMoney(remainMoney.subtract(payMoney));
                if (apply.getRemainMoney().compareTo(BigDecimal.ZERO) == 0) {
                    apply.setPayStatus(BusinessConstants.PAY_APPLY_PAY_STATUS_PAID);
                }else if (apply.getRemainMoney().compareTo(BigDecimal.ZERO) > 0) {
                    apply.setPayStatus(BusinessConstants.PAY_APPLY_PAY_STATUS_PART);
                }
                processPayApplyService.insertProcess(entity.getApplyId(), "", "打款:"+entity.getMoney()+"（元）");
                payApplyService.update(apply);
                List<PayApplyBuyDetail> payApplyBuyDetailList  =entity.getPayApplyBuyDetails();
                payRecordService.insert(entity);

                // 付款之后 插入 应付账款
                financeApService.addByPayRecord(entity);




                if (payApplyBuyDetailList != null && payApplyBuyDetailList.size() > 0) {
                    for (PayApplyBuyDetail payApplyBuyDetail : payApplyBuyDetailList) {
                        LvBuy lvBuy = lvBuyService.selectById(payApplyBuyDetail.getBuyId());
                        if (lvBuy != null) {
                            lvBuy.setFukuan(lvBuy.getFukuan().add(payApplyBuyDetail.getThisPayMoney()));
                            lvBuy.setShengyu(lvBuy.getShengyu().subtract(payApplyBuyDetail.getThisPayMoney()));
                        }
                        payMoney= payMoney.subtract(payApplyBuyDetail.getThisPayMoney());
                        if(BusinessConstants.PAY_APPLY_PAY_STATUS_PAID.equals(apply.getPayStatus())){
                            lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_DEPOSIT_PAID);
                        }
                        if(lvBuy.getShengyu().compareTo(BigDecimal.ZERO) == 0){
                            lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PAID);
                            // 全部付款之后 更新 采购单状态 为已付款
                            if (BusinessConstants.PAY_APPLY_TYPE_DEPOSIT.equals(apply.getType())) {
                                lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_DEPOSIT_PAID);
                            }
                            if (BusinessConstants.PAY_APPLY_TYPE_PART.equals(apply.getType())) {
                                lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PAID);
                            }
                            if (BusinessConstants.PAY_APPLY_TYPE_ALL.equals(apply.getType())) {
                                lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PAID);
                            }
                        }
                        lvBuyService.update(lvBuy);
                        payApplyBuyDetail.setPayRemain(payApplyBuyDetail.getPayRemain().subtract(payApplyBuyDetail.getThisPayMoney()));
                        payApplyBuyDetail.setPayMoney(payApplyBuyDetail.getPayMoney().add(payApplyBuyDetail.getThisPayMoney()));
                        if(payApplyBuyDetail.getPayRemain().compareTo(BigDecimal.ZERO) == 0){
                            payApplyBuyDetail.setPayStatus(BusinessConstants.STATUS_YES);
                        }else{
                            payApplyBuyDetail.setPayStatus(BusinessConstants.STATUS_NO);
                        }
                        payApplyBuyDetailService.update(payApplyBuyDetail);
                        PayRecordBuyDetail payRecordBuyDetail = new PayRecordBuyDetail();
                        payRecordBuyDetail.setPayApplyBuyDetailId(payApplyBuyDetail.getId());
                        payRecordBuyDetail.setPayRecordId(entity.getId());
                        payRecordBuyDetail.setMoney(payApplyBuyDetail.getThisPayMoney());
                        payRecordBuyDetailService.insert(payRecordBuyDetail);
                    }
                }

                if (payMoney.compareTo(BigDecimal.ZERO) > 0) {
                    String buyIds = apply.getBuyId();
                    String[] buyIdArray = buyIds.split(",");
                    for (String buyId : buyIdArray) {
                        LvBuy lvBuy = lvBuyService.selectById(buyId);
                        if (lvBuy != null) {
                            if(payMoney.compareTo(lvBuy.getShengyu()) >= 0){
                                payMoney= payMoney.subtract(lvBuy.getShengyu());
                                lvBuy.setFukuan(lvBuy.getFukuan().add(lvBuy.getShengyu()));
                                lvBuy.setShengyu(BigDecimal.ZERO);
                                lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PAID);
                                // 全部付款之后 更新 采购单状态 为已付款
                                if (BusinessConstants.PAY_APPLY_TYPE_DEPOSIT.equals(apply.getType())) {
                                    lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_DEPOSIT_PAID);
                                }
                                if (BusinessConstants.PAY_APPLY_TYPE_PART.equals(apply.getType())) {
                                    lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PAID);
                                }
                                if (BusinessConstants.PAY_APPLY_TYPE_ALL.equals(apply.getType())) {
                                    lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PAID);
                                }
                                lvBuyService.update(lvBuy);
                            }else{
                                lvBuy.setFukuan(lvBuy.getFukuan().add(payMoney));
                                lvBuy.setShengyu(lvBuy.getShengyu().subtract(payMoney));
                                lvBuyService.update(lvBuy);
                            }
                        }
                    }
                }
            }
        }
        return toAjax(1);
    }






    /**
     * 新增铁件 付款记录
     */
    @PreAuthorize("@ss.hasPermi('develop:PayRecord:add')")
    @Log(title = "付款记录", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping("/payAddByIron")
    public AjaxResult payAddByIron(@RequestBody PayRecord entity) {
        String applyId = entity.getApplyId();
        // 先判断 申请单 是否已经付款
        if (StringUtils.isBlank(applyId)) {
            return AjaxResult.error("申请单ID不能为空");
        }

        PayApply apply = payApplyService.selectById(applyId);
        if (BusinessConstants.PAY_APPLY_PAY_STATUS_PAID.equals(apply.getPayStatus())) {
            return AjaxResult.error("该申请单已经完成付款");
        }


        BigDecimal remainMoney = apply.getRemainMoney();
        BigDecimal payMoney = entity.getMoney();
        // 如果支付金额 大于剩余金额 则不能支付
        if (payMoney.compareTo(remainMoney) > 0) {
            return AjaxResult.error("支付金额不能大于剩余金额");
        }
        apply.setPaidMoney(apply.getPaidMoney().add(payMoney));
        apply.setRemainMoney(remainMoney.subtract(payMoney));
        if (apply.getRemainMoney().compareTo(BigDecimal.ZERO) == 0) {
            apply.setPayStatus(BusinessConstants.PAY_APPLY_PAY_STATUS_PAID);
        }else if (apply.getRemainMoney().compareTo(BigDecimal.ZERO) > 0) {
            apply.setPayStatus(BusinessConstants.PAY_APPLY_PAY_STATUS_PART);
        }
        processPayApplyService.insertProcess(entity.getApplyId(), "", "打款:"+entity.getMoney()+"（元）");
        payApplyService.update(apply);
        payRecordService.insert(entity);
        List<OrderIronRecordBuy> orderIronRecordBuys  =entity.getOrderIronRecordBuys();
        // 付款之后 插入 应付账款
        financeApService.addByPayRecord(entity);

        if (orderIronRecordBuys != null && !orderIronRecordBuys.isEmpty()) {
            for (OrderIronRecordBuy orderIronRecordBuy : orderIronRecordBuys) {
                LvBuy lvBuy = lvBuyService.selectById(orderIronRecordBuy.getBuyId());
                if (lvBuy != null) {
                    lvBuy.setFukuan(lvBuy.getFukuan().add(orderIronRecordBuy.getThisPayMoney()));
                    lvBuy.setShengyu(lvBuy.getShengyu().subtract(orderIronRecordBuy.getThisPayMoney()));
                }
                payMoney= payMoney.subtract(orderIronRecordBuy.getThisPayMoney());
                if(BusinessConstants.PAY_APPLY_PAY_STATUS_PAID.equals(apply.getPayStatus())){
                    lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_DEPOSIT_PAID);
                }
                if(lvBuy.getShengyu().compareTo(BigDecimal.ZERO) == 0){
                    lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PAID);
                    // 全部付款之后 更新 采购单状态 为已付款
                    if (BusinessConstants.PAY_APPLY_TYPE_DEPOSIT.equals(apply.getType())) {
                        lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_DEPOSIT_PAID);
                    }
                    if (BusinessConstants.PAY_APPLY_TYPE_PART.equals(apply.getType())) {
                        lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PAID);
                    }
                    if (BusinessConstants.PAY_APPLY_TYPE_ALL.equals(apply.getType())) {
                        lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PAID);
                    }
                }
                lvBuyService.update(lvBuy);
                orderIronRecordBuy.setPayRemain(orderIronRecordBuy.getPayRemain().subtract(orderIronRecordBuy.getThisPayMoney()));
                orderIronRecordBuy.setPayMoney(orderIronRecordBuy.getPayMoney().add(orderIronRecordBuy.getThisPayMoney()));
                if(orderIronRecordBuy.getPayRemain().compareTo(BigDecimal.ZERO) == 0){
                    orderIronRecordBuy.setPayStatus(BusinessConstants.STATUS_YES);
                }else{
                    orderIronRecordBuy.setPayStatus(BusinessConstants.STATUS_NO);
                }
                orderIronRecordBuyService.update(orderIronRecordBuy);
                PayRecordBuyDetail payRecordBuyDetail = new PayRecordBuyDetail();
                payRecordBuyDetail.setOrderIronRecordBuyId(orderIronRecordBuy.getId());
                payRecordBuyDetail.setPayRecordId(entity.getId());
                payRecordBuyDetail.setMoney(orderIronRecordBuy.getThisPayMoney());
                payRecordBuyDetailService.insert(payRecordBuyDetail);
            }
        }

        if (payMoney.compareTo(BigDecimal.ZERO) > 0) {
            String buyIds = apply.getBuyId();
            String[] buyIdArray = buyIds.split(",");
            for (String buyId : buyIdArray) {
                LvBuy lvBuy = lvBuyService.selectById(buyId);
                if (lvBuy != null) {
                    if (payMoney.compareTo(lvBuy.getShengyu()) >= 0) {
                        payMoney = payMoney.subtract(lvBuy.getShengyu());
                        lvBuy.setFukuan(lvBuy.getFukuan().add(lvBuy.getShengyu()));
                        lvBuy.setShengyu(BigDecimal.ZERO);
                        lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PAID);
                        // 全部付款之后 更新 采购单状态 为已付款
                        if (BusinessConstants.PAY_APPLY_TYPE_ALL.equals(apply.getType())) {
                            lvBuy.setPayApplyState(BusinessConstants.BUY_PAY_STATUS_PAID);
                        }
                        lvBuyService.update(lvBuy);
                    } else {
                        lvBuy.setFukuan(lvBuy.getFukuan().add(payMoney));
                        lvBuy.setShengyu(lvBuy.getShengyu().subtract(payMoney));
                        lvBuyService.update(lvBuy);
                    }
                }
            }


        }






        return toAjax(1);

    }
















    /**
     * 新增 运费 付款记录
     */
    @PreAuthorize("@ss.hasPermi('develop:PayRecord:add')")
    @Log(title = "付款记录", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping("/payAddForShipping")
    public AjaxResult payAddForShipping(@RequestBody PayRecord entity) {
        String applyId = entity.getApplyId();
        // 先判断 申请单 是否已经付款
        if (StringUtils.isBlank(applyId)) {
            return AjaxResult.error("申请单ID不能为空");
        }
        if (StringUtils.isNotBlank(applyId)) {
            PayApply apply = payApplyService.selectById(applyId);
            if (BusinessConstants.PAY_APPLY_PAY_STATUS_PAID.equals(apply.getPayStatus())) {
                return AjaxResult.error("该申请单已经完成付款");
            } else {
                BigDecimal remainMoney = apply.getRemainMoney();
                BigDecimal payMoney = entity.getMoney();
                // 如果支付金额 大于剩余金额 则不能支付
                if (payMoney.compareTo(remainMoney) > 0) {
                    return AjaxResult.error("支付金额不能大于剩余金额");
                }
                String[] buyIds = apply.getBuyId().split(",");
                if (buyIds.length > 1) {
                    for (String buyId : buyIds) {
                        LvBuy lvBuy = lvBuyService.selectById(buyId);
                        if (lvBuy != null) {
                            lvBuy.setShippingFeePaid(lvBuy.getShippingFeePaid().add(payMoney));
                            lvBuy.setShippingFeeRemain(lvBuy.getShippingFeeRemain().subtract(payMoney));
                        }
                        apply.setRemainMoney(remainMoney.subtract(payMoney));
                        apply.setPaidMoney(apply.getPaidMoney().add(payMoney));
                        apply.setPayStatus(BusinessConstants.PAY_APPLY_PAY_STATUS_PAID);
                        // 全部付款之后 更新 采购单 运费付款状态 为已付款
                        lvBuy.setShippingStatus(BusinessConstants.BUY_PAY_SHIPPING_PAID);
                        lvBuyService.update(lvBuy);
                    }
                } else {
                    LvBuy lvBuy = lvBuyService.selectById(apply.getBuyId());
                    if (lvBuy != null) {
                        lvBuy.setShippingFeePaid(lvBuy.getShippingFeePaid().add(payMoney));
                        lvBuy.setShippingFeeRemain(lvBuy.getShippingFeeRemain().subtract(payMoney));
                    }
                    if (payMoney.compareTo(remainMoney) < 0) {
                        apply.setPayStatus(BusinessConstants.PAY_APPLY_PAY_STATUS_PART);
                        apply.setPaidMoney(apply.getPaidMoney().add(payMoney));
                        apply.setRemainMoney(remainMoney.subtract(payMoney));
                        lvBuy.setShippingStatus(BusinessConstants.BUY_PAY_SHIPPING_PART);
                        lvBuyService.update(lvBuy);
                    }
                    if (payMoney.compareTo(remainMoney) == 0) {
                        apply.setPayStatus(BusinessConstants.PAY_APPLY_PAY_STATUS_PAID);
                        apply.setRemainMoney(remainMoney.subtract(payMoney));
                        apply.setPaidMoney(apply.getPaidMoney().add(payMoney));
                        // 全部付款之后 更新 采购单状态 为已付款
                        if (BusinessConstants.PAY_APPLY_CATEGORY_SHIPPING.equals(apply.getCategory())) {
                            lvBuy.setShippingStatus(BusinessConstants.BUY_PAY_SHIPPING_PAID);
                        }
                        lvBuyService.update(lvBuy);
                    }
                }
            }
            payApplyService.update(apply);
        }
        return toAjax(payRecordService.insert(entity));
    }


}
